<template>
  <div class="createProject">
    <a-spin :spinning="spinning">
      <div class="projectConetnt">
        <div class="createTitle">{{ $route.name }}</div>
        <properComp
          class="createProper"
          :isShow="isShow"
          :moduleType="'风险'"
          :projectTypeData="projectTypeData"
          :fromData="fromData"
          :requireObj="requireObj"
          :inputValue="inputValue"
          :beforeSubmit="beforeSubmit"
          @raidoChange="raidoChange"
          @showModal="showModal"
          @handProjectType="handProjectType"
        ></properComp>
        <common-modal
          :modalVisible="modalVisible"
          @handleOk="handleOk"
          @handCancel="handCancel"
          :selectType="'radio'"
          :itemArr="itemArr"
        ></common-modal>
        <a-drawer
        title="关联的规划项目"
        :width="'800px'"
        :visible="drawerVisible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onClose"
      >
        <div class="seerchBox" style="float: right; margin-bottom: 10px;z-index: 999;position: relative;">
          <global-search ref="globalSearch" :searchTableData="searchData1" @onSearch="onSearch1"></global-search>
        </div>
        <common-table
          :columns="columns1"
          :tableData="tableData1"
          :isRowsSelectVisible="isRowsSelectVisible"
          :selectType="selectType"
          :data-row-key="'oid'"
          @selectedRows="selectedRowsProject"
        ></common-table>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onClose">
            取消
          </a-button>
          <a-button type="primary" @click="onClose">
            确定
          </a-button>
        </div>
      </a-drawer>
      <a-drawer
        title="关联的规划书"
        :width="'800px'"
        :visible="drawerProjectVisible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onCloseProject"
      > 
        <div class="seerchBox" style="float: right; margin-bottom: 10px;z-index: 999;position: relative;">
          <global-search ref="globalSearch" :searchTableData="searchData" @onSearch="onSearch"></global-search>
        </div>
        <common-table
          :columns="columns2"
          :tableData="tableData"
          :isRowsSelectVisible="isRowsSelectVisible"
          :selectType="selectType"
          :data-row-key="'oid'"
          @selectedRows="selectedRowsBook"
        ></common-table>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1
          }"
        >
          <a-button :style="{ marginRight: '8px' }" @click="onCloseProject">
            取消
          </a-button>
          <a-button type="primary" @click="onCloseProject">
            确定
          </a-button>
        </div>
      </a-drawer>
      </div>
      <div class="footer">
        <div class="cancel" @click="cancelProject">取消</div>
        <div class="confirm self-primary-btn" @click="submitProject">提交</div>
      </div>
    </a-spin>
  </div>
</template>
<script>
import properComp from "@/components/propertyCommon";
import commonModal from "@/components/common/commonModal.vue";
import { getCreateProject, getRelatedPlanning, 
        getRelatedProject, getManagerMiddle, serveManager, 
        getProjectType, saveProject,
        searchUserIdMiddle, getProductCategoryByGroup} from "@api/singleProject"
import commonTable from "@/components/common/commonTable";
import {columnsProject, columnsPlanning} from "@/utils/constant/constant.js";
import { Message } from "ant-design-vue";
import globalSearch from "@/components/common/globalSearch"
let userinfo = JSON.parse(sessionStorage.getItem('userInfo'))
// import fromObj from "@/components/propertyCommon/data";
export default {
  name: "createProject",
  components: {
    properComp,
    commonModal,
    commonTable,
    globalSearch
  },
  data() {
    return {
      spinning: false,
      projectTypeData: [],
      fromData: [], //表单渲染
      requireObj: {}, // 表单提交验证
      isShow: false,
      // fromObj: {},
      modalId: "",
      modalVisible: false, // 弹框显示隐藏
      drawerVisible: false,
      drawerProjectVisible: false, // 关联的规划项目
      tableData: [], // 关联规划书数据
      searchData: [],
      searchData1: [],
      tableData1: [], // 关联规划项目数据
      isRowsSelectVisible: true,
      selectType: "radio",
      columns1: columnsProject, 
      columns2: columnsPlanning,
      userId: userinfo.loginName,
      selectBook: "",
      itemArr: [],
      objType: "",
      inputValue: {},
      isSave: false,
      isSubmit: false,
      checkedItem: [],
      checked: true, // 校验
      beforeSubmit: false,
    };
  },
  watch: {
    objType: {
      handler(n) {
        this.getCreateProject()
      }
    },
    "requireObj.ProjectSmallType": {
      handler(v) {
        if(v && this.objType === "cn.com.sany.ProcessImprovementProject") {
          let arr = v.indexOf("新工艺技术项目") != -1 ? ["RequirementsSource","TechnologySpecialty","IslightPlant"] : (v.indexOf("技改") != -1 ? ["ImportantGrade","RequirementsSource","ProjectBonus"] : ["ImportantGrade","ProjectBonus","TechnologySpecialty","isEquipmentModification"])
          this.removeHiddenField(arr)
        }
      }
    },
    //所属组织
    "requireObj.projectGroupReference": {
      handler(v) {
        let groupName = ""
        this.requireObj.ProductCategory = ""
        this.fromData.forEach(function(item) {
          item.rows.forEach(function(itm) {
            itm.items.forEach(function(itms) {
              if(itms.id == 'projectGroupReference') {
                for(let key in itms.selects) {
                  if(itms.selects[key] == v) {
                    groupName = key.split("-")[0]
                    return
                  }
                }
              }
            }) 
          })
        })
        getProductCategoryByGroup({groupName}).then(res => {
          // if()
          if(res.status == 200 && res.data.success) {
            let data = res.data.data
            let arrs = {}
            data.forEach(item => {
              let obj = {}
              obj[item] = item
              arrs = Object.assign({},arrs,obj)
            })
            this.fromData.forEach(function(item) {
              item.rows.forEach(function(itm) {
                itm.items.forEach(function(itms) {
                  if(itms.id == 'ProductCategory') {
                    itms.selects = arrs
                  }
                }) 
              })
            })
          } else {
            this.$message.error(res.data.message || "请求失败")
          }
        })
      }
    }
  },
  mounted() {
    this.getProjectType();
  },
  methods: {
    //将工艺类切换小类时隐藏的字段置空
    removeHiddenField(arr) {
      for (let key in this.requireObj) {
        if(arr.indexOf(key) != -1) {
          this.requireObj[key] = ""
        } 
      }
    },
    // 获取创建项目表单
    getCreateProject() {
      let params = {
        "objType": this.objType
      }
      getCreateProject(params).then(res=>{
        if(res.status === 200){
          // this.fromObj = res
          this.getFromData(res.data,this.objType);
        }else{
          Message.error('请求失败')
        }
      })
    },
      /* 全局搜索 */
    onSearch(tableVal, searchValue) {
      if (!searchValue) {
        this.tableData = this.searchData
      } else {
        this.tableData = tableVal
      }
    },
      /* 全局搜索 */
    onSearch1(tableVal, searchValue) {
      if (!searchValue) {
        this.tableData1 = this.searchData1
      } else {
        this.tableData1 = tableVal
      }
    },
    // 2.获取表单渲染数据
    getFromData(resData,objTypes) {
      let requiredArr = ["RequirementsSource","TechnologySpecialty","ImportantGrade","ProjectBonus","isEquipmentModification","IslightPlant"]
      // setTimeout(() => {
        let dataArr = resData.data;
        dataArr.forEach(itemData => {
          itemData.rows.forEach(eleData => {
            eleData.items.forEach(itData => {
              // 1. 将select数据对象转化为数组
              this.$set(itData, "selectArr", []);
              if (itData.selects && itData.selects !== null) {
                let obj = itData.selects;
                for (let key in obj) {
                  itData.selectArr.push(obj[key]);
                }
              }
              if(objTypes === "cn.com.sany.ProcessImprovementProject" && requiredArr.indexOf(itData.id) != -1) {
                itData.required = true;
              }
              // 2. 处理特殊情况
              switch (itData.id) {
                case "calendarReference":
                  itData.formType = "select";
                  break;
                case "projectTemplateReference":
                  itData.formType = "select";
                  break;
                case "projectGroupReference":
                  itData.formType = "select";
                  break;
                case "PlanningYear":
                  itData.formType = "select";
                  break;
                case "ReleatedPlanningBook":
                  itData.formType = "modal";
                  break;
                case "ReleatedPlanningProject":
                  itData.formType = "modal";
                  break;
                case "ProjectMananger":
                  itData.formType = "modal";
                  break;
                default:
                  break;
              }
              //工艺项目五小类加必填校验
              // 3.将id提取出来组成校验对象集
              this.$set(this.requireObj, itData.id, undefined);
              this.$set(this.inputValue, itData.id, undefined)
            });
          });
        });
        this.fromData = dataArr;
        this.checkProject()
        //   // 4. 判断特殊显示隐藏
        this.getSpecialVisible(this.fromData);
      // }, 1000);
    },
    // 1.获取项目类型数据
    getProjectType() {
      let params = {
        objType: "com.pisx.pmgt.project.PIProject",
        userId:  this.userId,
      }
      getProjectType(params).then(res=>{
        if(res.status === 200){
          this.projectTypeData = res.data.data
          this.objType = this.projectTypeData[0].name
        }else{
          this.projectTypeData =[]
        }
      })
    },
    // 选择项目
    handProjectType(val) {
      this.beforeSubmit = false
      this.objType = val
    },
    // 判断特殊显示隐藏
    getSpecialVisible(data) {
      data.forEach(item => {
        item.rows.forEach(ele => {
          ele.items.forEach(i => {
            if (this.requireObj["isPlanningProject"] === "是") {
              if (
                i.id === "PlanningYear" ||
                i.id === "ReleatedPlanningBook" ||
                i.id === "ReleatedPlanningProject"
              ) {
                i.required = true;
                this.$set(i, "specialVisible", false);
              }
            } else {
              if (
                i.id === "PlanningYear" ||
                i.id === "ReleatedPlanningBook" ||
                i.id === "ReleatedPlanningProject"
              ) {
                i.required = false;
                this.$set(i, "specialVisible", true);
              }
            }
          });
        });
      });
    },
    // 单选
    raidoChange(val) {
      this.getSpecialVisible(this.fromData);
    },
    // 弹窗显示
    showModal(val) {
      /**这里需要取当前点击input的id，来匹配requireObj里面的key值，在handeOk里面赋值 */
      for (let key in this.requireObj) {
        if (key === val.id) {
          this.modalId = key;
        }
      }
      for (let key in this.inputValue) {
        if (key === val.id) {
          this.modalId = key;
        }
      }
      if (val.id === "ProjectMananger") {
        this.modalVisible = true;
        this.getManager()
      } else if (val.id === "ReleatedPlanningBook") {
        this.relatedPlanning()
      } else if (val.id === "ReleatedPlanningProject") {
        this.relatedProject()
      }
    },
    // 项目经理
    getManager() {
      getManagerMiddle().then(res=>{
        if(res.data.staffList){
          const arr = res.data.staffList.split(',')
          const newStaffList = arr.filter((item,index) => {
            return arr.indexOf(item,0) ===index
          }) 
          let newArr = []
          let newList = []
          if(newStaffList.length > 10){
            newList = newStaffList.slice(-10)
            
          }else{
            newList = newStaffList
          }
          let params = {
            match: true,
            userIds: newList,
          }
          searchUserIdMiddle(params).then(res1=>{
            res1.data.map(item=>{
              item.checked = false
            })
            newArr.push(res1.data) 
            this.itemArr = newArr.flat()
          })
        }
      })
    },
    // 数组对象去重
    unique(arrData) {
      const res = new Map()
      return arrData.filter((arr) => !res.has(arr.userNo) && res.set(arr.userNo, 1))
    },
    // 关联规划书
    relatedPlanning() {
      if(!this.requireObj.projectGroupReference){
        Message.error("请先选择所属组织")
        return 
      }
      if(!this.requireObj.PlanningYear){
        Message.error("请先选择规划年份")
        return 
      }
      this.drawerProjectVisible = true
      const params = {
        userId: this.userId,
        oid: this.requireObj.projectGroupReference,
        plannYear: this.requireObj.PlanningYear,
     }
     getRelatedPlanning(params).then(res=>{
       if(res.status === 200){
         this.tableData = res.data.data
         this.searchData = res.data.data//按照创建时间降序排序
       }else{
         this.searchData = []
         Message.error("数据查询失败")
       }
     })
    },
    // 关联规划项目
    relatedProject() {
      if(!this.selectBook){
        Message.error("请先选择关联项目规划书")
        return 
      }
       this.drawerVisible = true;
      const params = {
        userId: this.userId,
        oid: this.selectBook,
     }
     getRelatedProject(params).then(res=>{
       if(res.status === 200){
          this.tableData1 = res.data.data
          this.searchData1 = res.data.data//按照创建时间降序排序
       }else{
         this.searchData1 = []//按照创建时间降序排序
          Message.error("数据查询失败")
       }
     })
    },
    // 添加项目经理
    handleOk(val) {
      this.inputValue[this.modalId] = val.name
      this.requireObj[this.modalId] = val.userId;
      let params = {
        staffList: val.userId,
        userId: this.userId
      }
      serveManager(params).then(res=>{
        if (res && res.status == 200) {
          if(res.result){
            Message.success('添加成功')
          }
        }
      })
      this.modalVisible = false;
    },
    handCancel() {
      this.modalVisible = false;
    },
    // 关闭抽屉(规划项目)
    onClose() {
      this.drawerVisible = false;
    },
    // 关闭抽屉(规划书)
    onCloseProject() {
      this.drawerProjectVisible = false;
    },
    // 单选规划书
    selectedRowsBook(val) {
      console.log(val, '448');
      this.selectBook = val[0].oid
      this.inputValue.ReleatedPlanningBook = val[0].name
      this.requireObj.ReleatedPlanningBook = val[0].oid
    },
    // 选择项规划项目
    selectedRowsProject(val){
      this.inputValue.ReleatedPlanningProject = val[0].name
      this.requireObj.ReleatedPlanningProject = val[0].oid
    },
    // 取消
    cancelProject() {
      this.routerPage()
    },
    // 关闭tab页签
    routerPage() {
      let tabArr = JSON.parse(sessionStorage.getItem('tabArr'))
      let newTabArr = tabArr.filter(iv => {
        return iv.path !== '/projectManage/createProject'
      })
      this.$store.commit("SET_TABS", newTabArr); // 赋值
      this.$router.push({
        path: '/projectManage'
      })
    },
    // reduceHiddenField(item,arr,removeArray) {
    //   if(this.requireObj[item] && arr.indexOf("item") != -1) {
    //     this.requireObj[item] = ""
    //   }
    //   if(!this.requireObj[item] && arr.indexOf(item) === -1){
    //     Message.error('带*的为必填项')
    //     console.log(2);
    //     this.checked = false
    //     return true
    //   }else{
    //     console.log(1);
    //     this.checked = true
    //   }
    // },
    reduceHiddenField(arr,removeArray) {
      let finalArray = [] 
      arr.forEach(item => {
        if(removeArray.indexOf(item) == -1) {
          finalArray.push(item)
        }
      })
      return finalArray
    },
    // 提交项目
    submitProject() {
      if(this.requireObj.ProjectBudget && Number(this.requireObj.ProjectBudget) !== Number(this.requireObj.ProjectBudget)){
        Message.error('项目预算类型只能为数值')
        return false
      }
      if(this.requireObj.ProjectBonus && Number(this.requireObj.ProjectBonus) !== Number(this.requireObj.ProjectBonus)){
        Message.error('项目奖金类型只能为数值')
        return false
      }
      this.beforeSubmit = true
      // this.checked = this.checkedItem.some(item => {
      //   return !this.requireObj[item]
      // })
      // if (this.checked) {
      //   Message.error('带*的为必填项')
      // }
      let checkedItem = JSON.parse(JSON.stringify(this.checkedItem))
      if( this.objType === "cn.com.sany.ProcessImprovementProject" && this.requireObj.ProjectSmallType ) {
        if(this.requireObj.ProjectSmallType.indexOf("新工艺技术项目") != -1) {
          checkedItem =  this.reduceHiddenField(this.checkedItem,["RequirementsSource","TechnologySpecialty","IslightPlant"])
        } else if(this.requireObj.ProjectSmallType.indexOf("技改") != -1) {
          checkedItem = this.reduceHiddenField(this.checkedItem,["ImportantGrade","RequirementsSource","ProjectBonus"])
        } else {
          checkedItem = this.reduceHiddenField(this.checkedItem,["ImportantGrade","ProjectBonus","TechnologySpecialty","isEquipmentModification"])
        }
      }  
      checkedItem.some(item => {
        if(!this.requireObj[item]){
          Message.error('带*的为必填项')
          this.checked = false
          return true
        }else{
          this.checked = true
        }
      })
      if(this.checked){
        if(this.isSubmit){
          return false
        }
        if(new Date(this.requireObj.planStartDate).valueOf() > new Date(this.requireObj.planEndDate).valueOf()){
          Message.error('计划开始时间不得大于计划完成时间')
          return false
        }
        var isModification = null
        if(this.requireObj.isEquipmentModification === "是") {
          if(this.requireObj.ProjectSmallType && this.requireObj.ProjectSmallType.indexOf("技改") != -1) {
            isModification =  false
          } else {
            isModification = true
            Message.error("涉及设备改造项目的项目，请选择技改项目（新工艺技术）项目小类！")
          }
        }
        if(isModification) return
        this.isSubmit = true
        this.spinning = true
        setTimeout(()=>{
          this.isSubmit = false
        }, 3000)
        let params = {
          userId: this.userId,
          values: this.requireObj,
          type: this.objType,
          oid: "",
        }
        saveProject(params).then(res => {
          if(res && res.status === 200) {
            if(res.data && res.data.success){
              Message.success("项目提交成功")
              this.spinning = false
              this.routerPage()
            } else {
              this.spinning = false
              Message.error(res.data.message)
              // Message.error('项目创建失败，请稍后再试！')
            }
          } else {
            this.spinning = false
            Message.error("项目提交异常")
          }
        })
      }
    },
    // 选出需要校验的项
    checkProject() {
      let arr = []
      this.fromData[0].rows.forEach(item =>{
        item.items.forEach(i =>{
          if(i.required){
            arr.push(i.id)
          }
        })
      })
      let idx = arr.findIndex(item => item === "projectShortName") 
      if(idx != -1) {
        arr.splice(idx, 1)
      }
      this.$set(this,"checkedItem",arr)
    }
  }
};
</script>
<style lang="less" scoped>
.createProject {
  position: relative;
  background-color: #fff;
  // height: 100%;
  // height: calc(100vh - 173px);
  min-height: 73vh;
  padding: 20px;
  .projectConetnt {
    .createTitle {
      font-size: 18px;
      color: #333;
      margin-bottom: 16px;
      font-weight: 550;
    }
    .createProper .fromBox .modalTitle {
      display: none;
    }
  }
  /deep/ .ant-spin-container{
    // height: calc(100vh - 173px);
    min-height: 73vh;
  }
  .footer {
    // position: absolute;
    // bottom: 20px;
    margin-top: 150px;
    display: flex;
    justify-content: flex-end;
    width: 100%;
    // height: 56px;
    border: none;
    border-radius: 1px;
    border: none;
    box-shadow: 2px 0px 4px #ccc;
    padding: 12px;
    .cancel {
      padding: 7px 20px;
      border: 1px solid #ccc;
      border-radius: 4px;
      text-align: center;
      line-height: 18px;
      cursor: pointer;
    }
    .confirm {
      margin-left: 15px;
      padding: 7px 20px;
      // background-color: #386bd7;
      border-radius: 4px;
      text-align: center;
      line-height: 18px;
      color: #fff;
      cursor: pointer;
    }
  }
}
</style>